import requests
import re
import json


def trans(word):
    uri = 'https://cn.bing.com/translator'
    gi = requests.get(uri).text
    ig = re.search(r'IG:"(.*?)"', gi).group(1)
    token = re.search(r'params_AbusePreventionHelper = (.*?);', gi).group(1)
    tokens = token.replace("[", "")
    js = tokens.split(',')
    t = js[1][1:33]
    url = 'https://cn.bing.com/ttranslatev3?isVertical=1&&IG={}&IID=translator.5027'.format(ig)
    data = {
        'fromLang': 'zh-Hans',
        'text': word,
        'to': 'en',
        'token': t,
        'key': js[0],
        'tryFetchingGenderDebiasedTranslations': 'true'
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
    }
    response = requests.post(url, data=data, headers=headers)
    response.raise_for_status()
    translations = response.json()[0]['translations']
    translated_text = translations[0]['text']
    print(translated_text)


word = input("请输入要翻译的文本：")
trans(word)